//  MyDocument.m
//  WorkTimer
//
//  Created by Gerhard Sletten on 06.01.06.
//  Copyright __MyCompanyName__ 2006 . All rights reserved.

#import "WTDocument.h"
NSString *WorkTimerPBoardType = @"WorkTimerPBoardType";

@implementation WTDocument

- (id)init 
{
    self = [super init];
    if (self != nil) {
		[self setHasUndoManager:YES];
        recordingSlide = nil;
		[[MyDocumentController sharedDocumentController] notifyOpen:self];
			
		time = [ [NSTimer scheduledTimerWithTimeInterval: 1
                    target:self
                    selector:@selector(recordTimer:)
                    userInfo:time
                    repeats:YES]
                    retain
                    ];
    }
    return self;
}

- (void)dealloc {
	[[NSNotificationCenter defaultCenter] removeObserver:self];
	
	[self timerStop];
	[recordingSlide release];
    [super dealloc];
}


- (void)close
{
   [self timerStop];
   [[MyDocumentController sharedDocumentController] notifyClose:self];
   [super close];
}
- (void)timerStop
{
	[self StopRecording:nil];
   if(time)
   {
       [time invalidate];
       [time release];
       time = 0;
   }
}


- (NSString *)windowNibName 
{
    return @"WTDocument";
}

- (void)windowControllerDidLoadNib:(NSWindowController *)windowController 
{
    [super windowControllerDidLoadNib:windowController];
	
	// Fetch all the entities from moc to see if there is any, no means 
	// that its a new document, and a new entity is inserted.
	NSManagedObjectContext *moc = [self managedObjectContext];
	NSEntityDescription *entityDescription = [NSEntityDescription
		entityForName:@"WTRecord" inManagedObjectContext:moc];
	NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
	[request setEntity:entityDescription];

	NSError *error = nil;
	NSArray *array = [moc executeFetchRequest:request error:&error];
	NSLog(@"log: %@",array);
	if ([array count] == 0)
	{
		NSLog(@"Nytt dokumemnt");
		[NSEntityDescription insertNewObjectForEntityForName:@"WTRecord" inManagedObjectContext:moc];
	} else {
		[ [NSTimer scheduledTimerWithTimeInterval: .01
                    target:self
                    selector:@selector(updateGUI)	//go to this method whenever the time comes
                    userInfo:nil
                    repeats:NO]
                    retain
                    ];
		
	}
	[startButton setEnabled:YES];
	[stopButton setEnabled:NO];
	//NSLog(@"TV target: %@",[tableView target]);
	[tableView setTarget:self];
	[tableView setDoubleAction:@selector(startEditSheet:)];

	
}	
	
- (IBAction)saveDocument:(id)sender
{
    if ([[self managedObjectContext] hasChanges])
    {
	[super saveDocument:sender];
    }
}

- (IBAction) StartRecording:(id)sender {
	
	//NSLog(@"userdef: %@", [[NSUserDefaults standardUserDefaults] valueForKey:@"WTRecordingMode"]);
	if (recordingSlide==nil && [arrayController selectionIndex]!=NSNotFound) {
		NSArray *selectedObjects = [arrayController selectedObjects];
		recordingSlide = (WTRecord *) [selectedObjects objectAtIndex:0];
		
		if([[NSUserDefaults standardUserDefaults] integerForKey:@"WTRecordingMode"] >= 1) {
			if (!isSameDay([recordingSlide valueForKey:@"date"],[NSDate date]) || [[NSUserDefaults standardUserDefaults] integerForKey:@"WTRecordingMode"] == 2) {
				NSManagedObjectContext *moc = [self managedObjectContext];
				recordingSlide = [NSEntityDescription insertNewObjectForEntityForName:@"WTRecord" inManagedObjectContext:moc];
				NSSortDescriptor *sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"date" ascending:NO] autorelease];
				[arrayController setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
				[arrayController setSelectionIndex:0];
			}
		}
		
		[startButton setEnabled:NO];
		[stopButton setEnabled:YES];
		
		[titleTextField setStringValue:[recordingSlide valueForKey:@"title"]];
		[recordingSlide setValue:[NSNumber numberWithBool:YES] forKeyPath:@"recording"];

	} else {
		NSBeep();
	}
	 
}

- (IBAction) StopRecording:(id)sender {
	if(recordingSlide!=nil) {
		[recordingSlide setValue:[NSNumber numberWithBool:NO] forKeyPath:@"recording"];
		recordingSlide=nil;
		[startButton setEnabled:YES];
		[stopButton setEnabled:NO];
		[titleTextField setStringValue:@""];
	} 
	
}

// NSTimer methods
- (void) recordTimer:(NSTimer *)timer
{
	if(recordingSlide!=nil) {
		NSNumber *tmpNumber = [recordingSlide valueForKeyPath:@"seconds"];
		int intNumber = [tmpNumber intValue];
		intNumber++;
		[recordingSlide setValue:[NSNumber numberWithInt:intNumber] forKeyPath:@"seconds"];
		[self updateGUI];
	
	}
}



// Copy
- (void)copy:(id)sender {
	if(recordingSlide!=nil) {
		return;
		NSBeep();
	}
    NSArray *selectedObjects = [arrayController selectedObjects];
    unsigned i, count = [selectedObjects count];
    if (count == 0) {
        return;
    }
    NSMutableArray *copyObjectsArray = [NSMutableArray arrayWithCapacity:count];
    NSMutableArray *copyStringsArray = [NSMutableArray arrayWithCapacity:count];
    WTRecord *record;
    for (i = 0; i < count; i++) {
        record = (WTRecord *)[selectedObjects objectAtIndex:i];
        [copyObjectsArray addObject:[record dictionaryRepresentation]];
        [copyStringsArray addObject:[record stringDescription]];
    }
	
	NSString *totalString = @"";
    totalString = [totalString stringByAppendingFormat:
        @"Total: %@", [timeTextField stringValue]];
	[copyStringsArray addObject:totalString];
    NSPasteboard *generalPasteboard = [NSPasteboard generalPasteboard];
    [generalPasteboard declareTypes:
            [NSArray arrayWithObjects:WorkTimerPBoardType, NSStringPboardType, nil]
                              owner:self];
    NSData *copyData = [NSArchiver archivedDataWithRootObject:copyObjectsArray];
    [generalPasteboard setData:copyData forType:WorkTimerPBoardType];
    [generalPasteboard setString:
        [copyStringsArray componentsJoinedByString:@"\n"]
                         forType:NSStringPboardType];
}

- (void)paste:(id)sender {
if(recordingSlide!=nil) {
		return;
		NSBeep();
	}
    NSPasteboard *generalPasteboard = [NSPasteboard generalPasteboard];
    NSData *data = [generalPasteboard dataForType:WorkTimerPBoardType];
    
	if (data == nil) {
        return;
    }
    
	NSManagedObjectContext *moc = [self managedObjectContext];
	
    NSArray *recordsArray = [NSUnarchiver unarchiveObjectWithData:data];
    unsigned i, count = [recordsArray count];
    for (i = 0; i < count; i++) {
        WTRecord *newRecord;
        newRecord = (WTRecord *)[NSEntityDescription insertNewObjectForEntityForName:@"WTRecord"
                inManagedObjectContext:moc];
		//NSLog(@"type: %@",[newRecord valueForKey:@"type.title"]);
        [newRecord setValuesForKeysWithDictionary:[recordsArray objectAtIndex:i]];
    }
}

- (void)cut:(id)sender {
    [self copy:sender];
    NSManagedObjectContext *moc = [self managedObjectContext];
	NSArray *selectedObjects = [arrayController selectedObjects];
    unsigned i, count = [selectedObjects count];
    for (i = 0; i < count; i++) {
        WTRecord *record;
        record = (WTRecord *)[selectedObjects objectAtIndex:i];
        [moc deleteObject:record];
    }
}

- (IBAction) toggleWindow:(id)sender {
	NSRect newRect = [mainWindow frame];
	if ([sender state] == 0) {
		newRect.size.width = 230;
		newRect.size.height = 80;
		newRect.origin.y += 280;

	} else {
		newRect.size.width = 430;
		newRect.size.height = 360;
		newRect.origin.y -= 280;
	}
	[mainWindow setFrame:newRect display:YES animate:YES];
}
	


- (IBAction) startEditSheet:(id)sender {
	[NSApp beginSheet:editSheet modalForWindow:mainWindow
        modalDelegate:self didEndSelector:NULL contextInfo:nil];
}
- (IBAction) endEditSheet:(id)sender {
	[editSheet orderOut:nil];
    [NSApp endSheet:editSheet];
	[self updateGUI];
}

- (void) updateGUI {
	NSNumber *totalSeconds = [arrayController valueForKeyPath:@"arrangedObjects.@sum.seconds"];
	//NSLog(@"updateGUI: %@",totalSeconds);
	[timeTextField setStringValue:intToTimeString([totalSeconds intValue])];
}

@end
